<?php
namespace control;
/*
*劳动合同类
*/

class workContractClass extends adIndexClass
{
    private const table = 'staff_contract';
    private const page = 'workContract';
    private const title = '劳动合同';
    public const contractLimitType=['固定期限','无固定期限'];


    /**
     * 查询表单
     *
     * @param string $workFlow
     * @return string
     */
    public function homeForm(string $workFlow = '待新签'): string
    {
        $html = '';
        //生成查询表单
        $html .=
            text(array('name' => 'name', 'title' => '姓名')) .
            selectMultiple(array("name" => "departmentId", "title" => "部门", "table" => "department", 'where' => "1=1 order by list asc", 'sqlField' => 'name', 'sqlId' => 'id')) .
            selectMultiple(array("name" => "jobId", "title" => "职位", "table" => "job", 'where' => "1=1 order by list asc", 'sqlField' => 'name', 'sqlId' => 'id')) .
            text(array('name' => 'idCard', 'title' => '身份证号')) .
            text(array('name' => 'tel', 'title' => '手机号')) .
            text(array("name" => "startTime", 'laydate' => ['range' => '~'], 'class' => 'width200', "title" => "入职日期-入职日期"));
        return $this->search($html, 'menu');
    }

    /*行政人事-出差记录-查询条件*/
    public function home($workFlow = '待新签')
    {
        $data = [
            "id" => "all",
            "menu" => [
                "draft" => "待新签",
                "signing" => "待续签",
                "effecting" => "生效中",
                "lift" => "已解除",
                "ending" => "已终止",
            ]
        ];
        $data['html'] = $this->homeForm($workFlow);
        return $this->tab($data);
    }

    /*行政人事-出差记录-查询结果*/
    public function homeSearch()
    {
        //全等查询数组
        $equal = array(
            "a.jobId" => $this->post('jobId'),
            "a.workFlow" => '待新签'
        );
        //like查询数组
        $like = array(
            "b.name" => $this->post('name'),
            "b.idCard" => $this->post('idCard'),
            "b.tel" => $this->post('tel'),
        );

        //初始化
        $and = "";
        if ($this->post('startTime')) {
            $and .= self::timeComparison($this->post('startTime'), field: 'entryDate');
        }
        if ($this->post('departmentId')) {
            $and .= " and a.jobId in (select id from job where departmentId = '" . $this->post('departmentId') . "')";
        }
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table . " as a join talent_pool as b on a.talentId = b.id",
            'field' => "a.*,b.name,b.idCard,b.tel",
            "where" => $where,
            "order" => "a.entryDate desc,a.orderNo desc"));
        //获取表头
        $tr[] = array('', '合同编号','姓名', "部门", '职位', "身份证号", "手机号", "入职日期", "入职天数", "在职状态");
        $url = root . "control/adIndex.html?cla=" . $this->get('cla') . "";
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "edit" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=edit&id=" . $array['id'] . "')"),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $staff = query('staff', "stid = '$array[staffId]'");
            $job = query('job', "id = '$array[jobId]'");
            //返回本行
            $tr[] = array($this->dominate($dominate), $array['orderNo'],$array['name'], departmentClass::getTypeName($job['departmentId']), $job['name'], $array['idCard'], $array['tel'], $array['entryDate'], $this->countDay($array['entryDate'], $this->date), $staff['state']);
        }
        //控件
        $button = "";

        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . space . $this->tableMany(array("tr" => $tr)) . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 编辑页
     * @return string
     */
    public function edit(): string
    {
        $id = $this->get('id') ?: suiji();
        $info = query(self::table, " id = '" . $id . "' ");
        if ($this->get('sourceId')) {
            //续签合同
            $info = query(self::table, " id = '" . $this->get('sourceId') . "' ");
        }
        $talent = query('talent_pool', "id = '$info[talentId]'");
        $staff = query('staff', "stid = '$info[staffId]'");
        //按钮
        $button[] = [
            "name" => "保存",
            "type" => "点击事件",
            "cla" => $this->get('cla'),
            "fun" => "subForm('" . self::page . "EditForm',root+'control/adIndex.html?cla=" . self::page . "&fun=editEdit')",
            "post" => ["id" => $id],
            'style' => 'li-btn-blue-bg',
        ];
        $job = query('job', "id = '$info[jobId]'");
        $departmentName = departmentClass::getTypeName($job['departmentId']);
        //表单
        $data['html'] = $this->layerEdit([
            "table" => [
                [
                    $this->tableShowButton($button)
                ],
                [
                    "<span class='small-title'>员工基本信息</span>"
                ],
                [
                    "姓名：" => $talent['name'],
                    "身份证号：" => $talent['idCard'],

                ],
                [
                    '手机号：' => $talent['tel'],
                    "部门：" => departmentClass::getTypeName($job['departmentId']),

                ],
                [
                    "职位：" => $job['name'],
                    '入职日期：' => $info['entryDate']
                ],
                [
                    '试用期至：' => $info['endDate'],
                    '在职状态：' => $staff['state'],
                ],
                [
                    "<span class='small-title'>合同信息</span>"
                ],
                [
                    must . "入职日期：" => text(["name" => "entryDate", 'laydate' => [], "value" => $info['entryDate']]),
                    must . "试用期至：" => text(["name" => "endDate", 'laydate' => [], "value" => $info['endDate']]),
                ],
                [
                    must . "合同类型：" => radio(["name" => "contractType", 'value' => explode('，', para('contractTypeOption')), "checked" => $info['contractType'] ?: '劳动合同']),
                    must . "合同期限：" => radio(array('name' => 'contractLimitType', 'checked' => $info['contractLimitType'], 'value' => ['固定期限' => '固定期限' . "&nbsp;<input name='contractYear' onblur='getEndDate(this)' min='0' style='padding:5px;width: 100px' type='number' value='{$info['contractYear']}'>&nbsp;月&nbsp;&nbsp;", '无固定期限' => '无固定期限'])),
                ],
                [
                    must . "合同签订日期：" => text(["name" => "signDate", 'laydate' => [], "value" => $info['signDate'] ?: $this->date]),
                    must . "合同起止日期：" => text(["name" => "signStartDate", 'laydate' => [], "value" => $info['signStartDate'] ?: $info['entryDate']]) . "至\n" . text(["name" => "signEndDate", 'laydate' => [], "value" => $info['signEndDate']]),
                ],
                [
                    must . "拟任职位：" => selectMultiple([
                        "name" => "jobId", "title" => "拟任职位",
                        'value' => $info['jobId'],
                        'sqlField' => 'name',
                        'sqlId' => 'id',
                        'table' => "job",
                        'where' => "1=1 order by list",
                        'change' => 'getJobInfo'
                    ]),
                    '职位类型：' => "<span id='jobType'>{$job['type']}</span>",
                ],
                [
                    '所属部门：' => "<span id='department'>$departmentName</span>",
                    "直属上级：" => selectMultiple([
                        "name" => "managerId", "title" => "直属上级",
                        'value' => $info['managerId'],
                        'sqlField' => 'name',
                        'sqlId' => 'stid',
                        'table' => "staff",
                    ]),
                ],
                [
                    must . "劳动报酬：" => text(["name" => "workSalary", "value" => $info['workSalary']]),
                    must . "社会保险：" => text(["name" => "insure", "value" => $info['insure']]),
                ],
                [
                    "备注：" => textarea(["name" => "workText", "value" => $info['text']]),
                ],
                [
                    "<div><span class='small-title'>合同附件</span></div>"
                ],
                [
                    fileUploadClass::addFileComponent($info['id'], '劳动合同', self::page, self::page . 'EditForm'),
                ]
            ],
            'hidden' => hidden(array('name' => 'id', 'value' => $id)) . hidden(array('name' => 'sourceId', 'value' => $this->get('sourceId'))),
            'button' => ' '
        ]);
        $data['html'] .= $this->editJs();
        //返回
        return $this->tab($data);
    }

    public function editJs()
    {
        return <<<eof
<script>
function getEndDate(e){
    let startDate = $("[name = 'entryDate']").val();
    let year = Number(e.value);
    let contractLimitType = $("[name='contractLimitType']:checked").val();
    if (contractLimitType ==='固定期限'){
        var now = new Date(startDate);
        var newDate = DateAdd(year, now);
         console.log(newDate)
        let str = newDate.Format("yyyy-MM-dd");
        $("[name='signEndDate']").val(str)
    }else{
         $("[name='signEndDate']").val('')
    }
}
function DateAdd(number, date) {
     date.setFullYear(date.getFullYear(),date.getMonth()+1+ number);
        return date;
    }
 function getJobInfo(e){
   let id = e.value;
   $.post(root+'control/adIndex.html?cla=talentPool&fun=getJobInfo',{id:id},function(res) {
        $("#jobType").html(res.data.jobType);
         $("#department").html(res.data.department);
   },'json')
 }

</script>
eof;

    }

    /**
     * 计算日期间的天数
     * @param $startDate
     * @param $endDate
     * @return string
     * @throws Exception
     */
    public function countDay($startDate, $endDate): string
    {
        $dStart = new \DateTime($startDate);
        $dEnd = new \DateTime($endDate);
        $dDiff = $dStart->diff($dEnd);
        return $dDiff->format('%r%a');
    }

    public function signing(): bool|string
    {
        $json['html'] = $this->homeForm('待续签');
        return json_encode($json, 320);
    }

    public function signingSearch(): bool|string
    {
        $warnDay = para('workContractWarnDay');
        //全等查询数组
        $equal = array(
            "a.jobId" => $this->post('jobId'),
            "contractLimitType" => '固定期限',
        );
        //like查询数组
        $like = array(
            "b.name" => $this->post('name'),
            "b.idCard" => $this->post('idCard'),
            "b.tel" => $this->post('tel'),
        );

        //找生效中且合同结束日期小于提醒天数的 和 合同正常终止但未离职的
        $and = " and isClose = 0 and ((a.workFlow = '生效中' and DATEDIFF(signEndDate,DATE_FORMAT(now(),'%Y-%m-%d')) <= '$warnDay') or (a.workFlow = '已终止' and isQuit = 0))";
        if ($this->post('startTime')) {
            $and .= self::timeComparison($this->post('startTime'), field: 'entryDate');
        }
        if ($this->post('departmentId')) {
            $and .= " and a.jobId in (select id from job where departmentId = '" . $this->post('departmentId') . "')";
        }
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table . " as a join talent_pool as b on a.talentId = b.id",
            'field' => "a.*,b.name,b.idCard,b.tel",
            "where" => $where,
            "order" => "a.entryDate desc,a.orderNo desc"));
        //获取表头
        $tr[] = array('', '合同编号','姓名', "部门", '职位', "身份证号", "手机号", "入职日期", "入职天数", "在职状态");
        //获取表头
        $url = root . "control/adIndex.html?cla=" . $this->get('cla') . "";
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $staff = query('staff', "stid = '$array[staffId]'");
            $job = query('job', "id = '$array[jobId]'");
            //返回本行
            $tr[] = array($this->dominate($dominate), $array['orderNo'],$array['name'], departmentClass::getTypeName($job['departmentId']), $job['name'], $array['idCard'], $array['tel'], $array['entryDate'], $this->countDay($array['entryDate'], $this->date), $staff['state']);
        }
        //返回
        $json['html'] = $page['hint'] . "<form name='listForm'>" . space . $this->tableMany(array("tr" => $tr)) . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    public function effecting()
    {
        $json['html'] = $this->homeForm('生效中');
        return json_encode($json, 320);
    }

    public function effectingSearch()
    {
        //全等查询数组
        $equal = array(
            "a.jobId" => $this->post('jobId'),
            "a.workFlow" => '生效中',
//            "contractLimitType" => '固定期限',
        );
        //like查询数组
        $like = array(
            "b.name" => $this->post('name'),
            "b.idCard" => $this->post('idCard'),
            "b.tel" => $this->post('tel'),
        );

        //初始化
        $and = " and isClose = 0";
        if ($this->post('startTime')) {
            $and .= self::timeComparison($this->post('startTime'), field: 'entryDate');
        }
        if ($this->post('departmentId')) {
            $and .= " and a.jobId in (select id from job where departmentId = '" . $this->post('departmentId') . "')";
        }
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table . " as a join talent_pool as b on a.talentId = b.id",
            'field' => "a.*,b.name,b.idCard,b.tel",
            "where" => $where,
            "order" => "a.entryDate desc,a.orderNo desc"));
        //获取表头
        $tr[] = array('','合同编号', '姓名', "部门", '职位', "身份证号", "手机号", "入职日期", "入职天数", "在职状态");
        //获取表头
        $url = root . "control/adIndex.html?cla=" . $this->get('cla') . "";
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $staff = query('staff', "stid = '$array[staffId]'");
            $job = query('job', "id = '$array[jobId]'");
            //返回本行
            $tr[] = array($this->dominate($dominate), $array['orderNo'],$array['name'], departmentClass::getTypeName($job['departmentId']), $job['name'], $array['idCard'], $array['tel'], $array['entryDate'], $this->countDay($array['entryDate'], $this->date), $staff['state']);
        }
        //返回
        $json['html'] = $page['hint'] . "<form name='listForm'>" . space . $this->tableMany(array("tr" => $tr)) . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    public function lift()
    {
        $json['html'] = $this->homeForm('已解除');
        return json_encode($json, 320);
    }

    public function liftSearch()
    {
        //全等查询数组
        $equal = array(
            "a.jobId" => $this->post('jobId'),
            "a.workFlow" => '已解除',
        );
        //like查询数组
        $like = array(
            "b.name" => $this->post('name'),
            "b.idCard" => $this->post('idCard'),
            "b.tel" => $this->post('tel'),
        );

        //初始化
        $and = "";
        if ($this->post('startTime')) {
            $and .= self::timeComparison($this->post('startTime'), field: 'entryDate');
        }
        if ($this->post('departmentId')) {
            $and .= " and a.jobId in (select id from job where departmentId = '" . $this->post('departmentId') . "')";
        }
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table . " as a join talent_pool as b on a.talentId = b.id",
            'field' => "a.*,b.name,b.idCard,b.tel",
            "where" => $where,
            "order" => "a.entryDate desc,a.orderNo desc"));
        //获取表头
        $tr[] = array('', '合同编号','姓名', "部门", '职位', "身份证号", "手机号", "入职日期", "入职天数", "在职状态");
        //获取表头
        $url = root . "control/adIndex.html?cla=" . $this->get('cla') . "";
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $staff = query('staff', "stid = '$array[staffId]'");
            $job = query('job', "id = '$array[jobId]'");
            //返回本行
            $tr[] = array($this->dominate($dominate),$array['orderNo'], $array['name'], departmentClass::getTypeName($job['departmentId']), $job['name'], $array['idCard'], $array['tel'], $array['entryDate'], $this->countDay($array['entryDate'], $this->date), $staff['state']);
        }
        //返回
        $json['html'] = $page['hint'] . "<form name='listForm'>" . space . $this->tableMany(array("tr" => $tr)) . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    public function ending()
    {
        $json['html'] = $this->homeForm('已终止');
        return json_encode($json, 320);
    }

    public function endingSearch()
    {
        //全等查询数组
        $equal = array(
            "a.jobId" => $this->post('jobId'),
            "a.workFlow" => '已终止',
            "contractLimitType" => '固定期限',
        );
        //like查询数组
        $like = array(
            "b.name" => $this->post('name'),
            "b.idCard" => $this->post('idCard'),
            "b.tel" => $this->post('tel'),
        );

        //初始化
        $and = "";
        if ($this->post('startTime')) {
            $and .= self::timeComparison($this->post('startTime'), field: 'entryDate');
        }
        if ($this->post('departmentId')) {
            $and .= " and a.jobId in (select id from job where departmentId = '" . $this->post('departmentId') . "')";
        }
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table . " as a join talent_pool as b on a.talentId = b.id",
            'field' => "a.*,b.name,b.idCard,b.tel",
            "where" => $where,
            "order" => "a.entryDate desc,a.orderNo desc"));
        //获取表头
        $tr[] = array('','合同编号', '姓名', "部门", '职位', "身份证号", "手机号", "入职日期", "入职天数", "在职状态");
        //获取表头
        $url = root . "control/adIndex.html?cla=" . $this->get('cla') . "";
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $staff = query('staff', "stid = '$array[staffId]'");
            $job = query('job', "id = '$array[jobId]'");
            //返回本行
            $tr[] = array($this->dominate($dominate), $array['orderNo'],$array['name'], departmentClass::getTypeName($job['departmentId']), $job['name'], $array['idCard'], $array['tel'], $array['entryDate'], $this->countDay($array['entryDate'], $this->date), $staff['state']);
        }
        //返回
        $json['html'] = $page['hint'] . "<form name='endingForm'>" . space . $this->tableMany(array("tr" => $tr)) . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    public function judgeIsDiff($info, $field, $annotation)
    {
        $text = '';
        foreach ($field as $k => $val) {
            if ($val != $info[$k]) {
                $text .= $annotation[$k] . "从" . $info[$k] . '更新至' . $val . "<br>";
            }
        }
        if ($text) {
            $this->insertRecord(array(
                'text' => $text,
                'contractId' => $info['id'],
            ));
        }
    }

    public function insertRecord($field): string
    {
        $field = array_merge(
            $field,
            [
                'id' => suiji(),
                'name' => $this->control['name']
            ]
        );
        return static::insert(array(
            'table' => 'staff_contract_change',
            'field' => $field
        ));
    }

    /*编辑*/
    public function editEdit()
    {
        $id = $this->post('id');
        $sourceId = $this->post('sourceId');
        $field = [
            'jobId' => $this->post('jobId'),
            'managerId' => $this->post('managerId'),
            'entryDate' => $this->post('entryDate'),
            'endDate' => $this->post('endDate'),
            'text' => $this->post('workText'),
            'contractType' => $this->post('contractType'),
            'contractYear' => $this->post('contractYear'),
            'contractLimitType' => $this->post('contractLimitType'),
            'workSalary' => $this->post('workSalary'),
            'insure' => $this->post('insure'),
            'signDate' => $this->post('signDate'),
            'signStartDate' => $this->post('signStartDate'),
            'signEndDate' => $this->post('signEndDate'),
        ];
        $annotation = [
            'jobId' => '拟任职位',
            'managerId' => '直属上级',
            'entryDate' => '入职日期',
            'endDate' => '试用期至',
            'text'=>'备注',
            'contractType' => '合同类型',
            'contractYear' => '合同期限',
            'contractLimitType' => '合同期限类型',
            'signDate' => '合同签订日期',
            'signStartDate' => '合同起始日期',
            'signEndDate' => '合同结束日期',
            'workSalary' => '劳动报酬',
            'insure' => '社会保险',
        ];
        $rules = [
            'jobId' => 'required',
            'entryDate' => 'required',
            'endDate' => 'required',
            'contractType' => 'required',
            'contractLimitType' => 'required',
            'signDate' => 'required|date',
            'signStartDate' => 'required|date',
            'workSalary' => 'required',
            'insure' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $entryResult = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($entryResult === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        $info = query(self::table, " id = '" . $id . "' ");
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "您还没有编辑权限";
        } elseif (empty($info['id']) && empty($sourceId)) {
            $json['warn'] = '未找到此合同';
        } elseif ($field['contractLimitType'] == '固定期限' && empty($field['signEndDate'])) {
            $json['warn'] = '请选择合同截止日期';
        } elseif ($field['contractLimitType'] == '固定期限' && strtotime($field['signEndDate']) <= strtotime($field['signStartDate'])) {
            $json['warn'] = '合同截止日期不能小于起始日期';
        } else {
            if ($field['contractLimitType'] == '无固定期限') {
                $field['contractYear'] = 0;
                $field['signEndDate'] = '';
            }
            if (empty($info['id']) && $sourceId) {
                $source = query(self::table, "id = '$sourceId'");

                $department = query('department', " id = '{$this->controlJob['departmentId']}'");
                $field = array_merge($field, [
                    'id' => suiji(),
                    'talentId' => $source['talentId'],
                    'staffId' => $source['staffId'],
                    'workFlow' => '生效中',
                    'stid' => $this->control['stid'],
                    'deptName' => $department['name'],
                ]);
                $userNo = codeTemplateClass::generateCode('workContract',[
                    'prefix' => 'LDHT' . date('Ymd'),
                    'table' => 'staff_contract',
                    'field' => 'orderNo',
                    'where' => '',
                ],$field);
                $field['orderNo'] = $userNo;
                $json['warn'] = insert(array("table" => self::table, "field" => $field));
            } else {
                $userNo = $info['orderNo'];
                $json['warn'] = update(array("table" => self::table, "field" => $field, "where" => "id = '$info[id]'"));
            }
            if (in_array($json['warn'], array("新增成功", "更新成功"))) {
                if ($sourceId) {
                    $oldField['isClose'] = 1;
                    //续签
                    $oldContract = query(self::table, "id = '$sourceId'");
                    if ($oldContract['signEndDate'] >= $field['signStartDate']) {
                        $oldField['workFlow'] = '已终止';
                    }
                    update(array('table' => self::table, 'field' => $oldField, 'where' => "id = '$oldContract[id]'"));
                    $this->insertRecord(array(
                        'contractId'=> $sourceId,
                        'text'=>'新合同【'.$userNo.'】生效，此合同终止'
                    ));
                }else{
                    $this->judgeIsDiff($info, $field, $annotation);
                }
                //附件
                $fileIdArr = $this->post('fileId');
                if (is_array($fileIdArr)) {
                    update(array('table' => 'file', 'field' => ['targetId' => $id], 'where' => " targetId = '' and id in ('" . implode("','", $fileIdArr) . "')"));
                }
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "ID：" . $id;
                $this->logText(array("type" => self::page, "text" => $text));
                //返回
                $_SESSION['warn'] = $sourceId ? '续签成功' : $json['warn'];
                $json['warn'] = 2;
            }

        }

        $json['href'] = root . "control/adIndex.html?cla=" . self::page . "&fun=detail&id=" . $id;
        resp:
        return json_encode($json, 320);
    }


    /*出差详情*/
    public function detail(): string
    {
        //定义参数
        if (empty($this->get('id'))) {
            $html = '未找到此' . self::title;
        } else {
            $info = query(self::table, " id = '" . $this->get('id') . "' ");
            if (empty($info['id'])) {
                $html = "未找到此记录";
            } else {
                //菜单
                $data = array(
                    "id" => $info['id'],
                );

                $button = [];
                //按钮
                if ($this->power(self::page, "edit") && $info['workFlow'] == '待新签') {
                    //按钮
                    $button[] = [
                        "name" => "提交",
                        "type" => "弹出层",
                        "cla" => $this->get('cla'),
                        "fun" => "operate",
                        "post" => ["act" => 'commit', "id" => $info['id']],
                        'style' => 'li-btn-blue-bg',
                    ];
                }
                $warnDay = para('workContractWarnDay');
                if (!$info['isClose'] && ($info['workFlow'] == '待续签' || ($info['workFlow'] == '生效中' && $this->countDay($this->date,$info['signEndDate']) < $warnDay) || ($info['workFlow']=='已终止' && !$info['isQuit'])) && $this->power(self::page, "edit")) {
                    //按钮
                    $button[] = [
                        "name" => "续签",
                        "type" => "顶部页卡",
                        "title" => "劳动合同详情",
                        "url" => $this->root . "control/adIndex.html?cla={$this->get('cla')}&fun=edit&sourceId=" . $info['id'],
                    ];
                }

                if ($this->power(self::page, "edit") && in_array($info['workFlow'], ['待新签', '待续签'])) {
                    //按钮
                    $button[] = [
                        "name" => "编辑",
                        "type" => "顶部页卡",
                        "title" => "编辑",
                        "url" => $this->root . "control/adIndex.html?cla={$this->get('cla')}&fun=edit&id=" . $info['id'],
                    ];
                }
                $tr[] = ['变更日期', '变更人', '变更内容'];
                $all = find(array('table' => 'staff_contract_change', 'where' => "contractId = '$info[id]' order by time desc"));
                foreach ($all['array'] as $array) {
                    $tr[] = [$array['time'], $array['name'], $array['text']];
                }

                $staff = query('staff', "stid = '$info[staffId]'");
                $talent = query('talent_pool', "id = '$info[talentId]'");
                $job = query('job', "id = '$info[jobId]'");
                $staffEntry = query('staff_entry_record', "talentId = '$talent[id]' order by time desc");
                $staffFormal = query('staff_formal', "staffId = '$info[staffId]' order by time desc");
                //生成表单
                $data['html'] = $this->tableShow(array(
                    "button" => $button,
                    '员工基本信息' => array(
                        array(
                            "姓名" => $talent['name'],
                            "身份证号" => $talent['idCard'],
                            "手机号" => $talent['tel'],
                        ),
                        array(
                            "部门" => departmentClass::getTypeName($job['departmentId']),
                            "职位" => $job['name'],
                            "入职日期" => $staffEntry['entryDate'],
                        ),
                        array(
                            "转正日期" => $staffFormal['confirmDate'],
                            "在职状态" => $staff['state'],
                        ),
                    ),
                    '合同信息' => array(
                        array(
                            "入职日期" => $info['entryDate'],
                            "试用期至" => $info['endDate'],
                        ),
                        array(
                            "合同类型" => $info['contractType'],
                            "合同期限" => $info['contractLimitType'] == '固定期限' ? $info['contractLimitType'] . $info['contractYear'] . '个月' : $info['contractLimitType'],
                            "劳动报酬" => $info['workSalary'],
                        ),
                        array(
                            "社会保险" => $info['insure'],
                        ),
                        array(
                            "合同签订日期" => $info['signDate'],
                            "合同起止日期" => $info['signStartDate'] . '至' . ($info['contractLimitType'] == '固定期限'?$info['signEndDate']:$info['contractLimitType']),
                            "合同解除/终止日期" => $info['stopDate'],
                        ),
                        array(
                            "备注" => $info['text'],
                        ),
                    ),
                    '附件' => array(
                        array(
                            fileUploadClass::showFile($info['id'])
                        ),
                    ),
                    '变更记录' => array(
                        array(
                            $this->tableMany(['tr' => $tr])
                        )
                    ),
                    '系统信息' => array(
                        array(
                            '合同编号' => $info['orderNo'],
                            '合同状态' => $info['workFlow'],
                        ),
                        array(
                            '创建人' => self::findStaff($info['stid']),
                            '创建时间' => $info['time'],
                            '更新时间' => $info['updateTime'],
                        )
                    )
                ));
                //生成页面
                $html = $this->tab($data);
            }
        }
        //返回
        return $html;
    }


    /**
     * 提交
     */
    public function commitEdit()
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'workFlow' => '生效中',
        ];
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此劳动合同';
        } elseif ($info['workFlow'] != '待新签') {
            $json['warn'] = '此合同不是待新签状态，不能提交';
        } else {
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                $this->insertRecord(array(
                    'text' => $this->control['name'] . "提交了参保信息",
                    'contractId' => $info['id']
                ));
                //生成劳动合同到期提醒
//                $setting = self::getSettingValue('laborContract');
//                $startDay = date("Y-m-d",strtotime("-".$setting['threshold']." days", strtotime($info['signEndDate'])));
//                foreach ($setting['member'] as $item){
//                    backlogIn([
//                        "stid"      => $item,
//                        "type"      => '提醒消息',
//                        "typeId"    => $info['id'],
//                        "text"      => "劳动合同" . "【" . $info['orderNo'] . "】将在".$info['signEndDate']."到期",
//                        "startDay"  => $startDay,
//                        "targetCla" => 'workContract',
//                        "targetFun" => 'detail',
//                    ]);
//                }
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = '提交成功，合同生效中';
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if ($info['state'] == '已确认') {
                    $warn = "删除失败：已确认，暂不能删除";
                } else {
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    delete(array("table" => "auditing_follow", "where" => " typeId = '$id' "));
                    //返回
                    $warn = "删除成功";
                    $x++;
                }
                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $power = $word = '';
        switch ($act) {
            case 'confirm':
                $act = 'confirm';
                $msg = '确认';
                $title = '是否已确认此' . self::title . '，确认后将不可修改？';
                $function = 'confirmEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            case 'commit':
                $act = 'edit';
                $msg = '编辑';
                $title = '是否确认提交此' . self::title . '？';
                $function = 'commitEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            case 'cancel':
                $act = 'cancel';
                $msg = '撤回';
                $title = '是否确认撤回此' . self::title . '？';
                $function = 'cancelEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'word' => $word
            ]);
        }

        resp:
        return json_encode($json, 320);
    }


}
